package com.bdqn.ch02.sl;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class SL06 {
    Document doc=null;
    public void getDocument(){
        //得到DOM解析器的工厂实列
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //获取解析器工厂
        try {
            //从DOM工厂获取DOM解析器
            DocumentBuilder db = dbf.newDocumentBuilder();
            //解析XML文档，得到一个Document，即DOM树
             doc= db.parse("src/dao/PhoneInfo2.xml");

        } catch (ParserConfigurationException e) {
            e.fillInStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
    }
    public void showInfo(){
       NodeList list  = doc.getElementsByTagName("Brand");
       for(int i=0;i<list.getLength();i++){
           Element brandElement = (Element) list.item(i);
           String brandName = brandElement.getAttribute("name");
           if (brandName.equals("SAMSUNG")){
               brandElement.getParentNode().removeChild(brandElement);//修改属性
           }
           //保存XML文件
           TransformerFactory transformerFactory=TransformerFactory.newInstance();
           try {
               Transformer transformer=transformerFactory.newTransformer();
               DOMSource domSource=new DOMSource(doc);
               //设置编码类型
               transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
               StreamResult result=new StreamResult(new FileOutputStream("src/dao/PhoneInfo2.xml"));
               transformer.transform(domSource,result);
           } catch (TransformerConfigurationException e) {
               throw new RuntimeException(e);
           } catch (FileNotFoundException e) {
               throw new RuntimeException(e);
           } catch (TransformerException e) {
               throw new RuntimeException(e);
           }
       }
    }

    public static void main(String[] args) {
        SL06 Parse=new SL06();
        Parse.getDocument();
        Parse.showInfo();
    }
}
